package com.support.SQLite;

import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import com.project.bean.News;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class NewsDao extends BaseDao {

	private List<News> newsList;

	public NewsDao(Context context) {
		init(context);
	}

	public SQLiteDatabase getDB() {
		return db;
	}

	public SQLHelper getDBHelper() {
		return dbHelper;
	}

	public long insert(News news) {
		long id = insert(NewsEnum.TAB_NAME + "", News2ContentValues(news));
		news.setId(id);
		return id;
	}

	public void insert(List<News> newsList) {
		for (News news : newsList) {
			insert(news);
		}
	}

	public ContentValues News2ContentValues(News news) {
		ContentValues values = new ContentValues();
		values.put(NewsEnum.NewsID + "", news.getNewsId() + "");
		values.put(NewsEnum.DES + "", news.getDescription() + "");
		values.put(NewsEnum.Other + "", news.getOther() + "");
		values.put(NewsEnum.Photo + "", news.getPhoto() + "");
		values.put(NewsEnum.Title + "", news.getTitle() + "");
		return values;
	}

	/** 有可能返回null */
	public List<News> cursors2BeanArray(Cursor cursor) {
		if (!cursor.moveToFirst()) {
			return null;
		}
		if (newsList == null) {
			newsList = new ArrayList<News>();
		}
		newsList.clear();
		while (!cursor.isAfterLast()) {
			News news = cursor2Bean(cursor);
			if (news != null)
				newsList.add(news);
			cursor.moveToNext();
		}
		return newsList;
	}

	/** 可能会返回null **/
	public News cursor2Bean(Cursor cursor) {
		News news = null;
		if (cursor.moveToFirst()) {
			news = new News();
			news.setId(cursor.getLong(0));
			news.setDescription(new StringBuilder(cursor.getString(1)));
			news.setPhoto(new StringBuilder(cursor.getString(2)));
			news.setTitle(new StringBuilder(cursor.getString(3)));
			news.setTitle(new StringBuilder(cursor.getString(4)));
		}
		return news;
	}

	/**
	 * 一定要修改cursor2Bean {@link com.support.SQLite.NewsDao}
	 */
	enum NewsEnum {
		TAB_NAME("news_tab"), NewsID("news_id"), DES("description"), Photo("photo"), Title("title"), Other("other");
		private String column;

		private NewsEnum(String column) {
			this.column = column;
		}

		public String getColumnName() {
			return column;
		}

		public static List<String> getAllcolumns() {
			List<String> columns = new ArrayList<String>();
			for (NewsEnum newsColumn : EnumSet.range(NewsEnum.NewsID, NewsEnum.Other)) {
				columns.add(newsColumn + "");
			}
			return columns;
		}
	}
}
